import { createRouter, createWebHistory } from 'vue-router'
import { getComponents, getRouteName } from '/@/utils/helper'

const pages = import.meta.glob('../pages/**/*.vue')
const components = getComponents(pages)

const routes = [
  {
    path: '/',
    component: () => import('/@/layouts/Default.vue'),
    children: Object.keys(components)
      .map(path => {
        return {
          path,
          name: getRouteName(path),
          component: components[path]
        }
      })
  },
  {
    path: '/404',
    name: '404',
    component: () => import('/@/exception/404.vue')
  },
  {
    path: '/:catchAll(.*)',
    redirect: '/404'
  }
]

export const loadingBarApiRef = {}

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  scrollBehavior: () => ({ left: 0, top: 0 }),
  routes
})

router.beforeEach((to, from, next) => {
  if (!from || to.path !== from.path) {
    if (loadingBarApiRef.value) {
      loadingBarApiRef.value.start()
    }
  }
  next()
})

router.afterEach((to, from) => {
  if (!from || to.path !== from.path) {
    if (loadingBarApiRef.value) {
      loadingBarApiRef.value.finish()
    }
  }
})

export function setupRouter(app) {
  app.use(router)
}

export default router
